<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-if="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="账号名称" prop="accountName">
              <el-input v-model="queryParams.accountName" placeholder="请输入账号名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="支付平台" prop="payTypeId">
              <!-- <el-input v-model="queryParams.payTypeId" placeholder="请输入支付平台" clearable @keyup.enter="handleQuery" /> -->
              <el-select v-model="queryParams.payTypeId" clearable>
                <el-option v-for="item in payList" :key="item.name" :label="item.name" :value="item.typeId"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="供应商" prop="supplierId">
              <el-select v-model="queryParams.supplierId" filterable clearable>
                <el-option v-for="item in supplierList" :label="item.userName" :value="item.userId"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="域名" prop="domain">
              <el-input v-model="queryParams.domain" placeholder="请输入域名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" clearable>
                <el-option value="1" label="活跃"></el-option>
                <el-option value="2" label="封禁"></el-option>
                <el-option value="3" label="失败"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否生成订单" prop="generateOrder">
              <el-select v-model="queryParams.generateOrder" clearable>
                <el-option label="是" value="1"></el-option>
                <el-option label="否" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否生成产品" prop="generateProduct">
              <el-select v-model="queryParams.generateProduct" clearable>
                <el-option label="是" value="1"></el-option>
                <el-option label="否" value="0"></el-option>
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="账号配置" prop="config">
              <el-input v-model="queryParams.config" placeholder="请输入账号配置" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="代理ID" prop="agentId">
              <el-input v-model="queryParams.agentId" placeholder="请输入代理ID" clearable @keyup.enter="handleQuery" />
            </el-form-item> -->
            <el-form-item label="备注" prop="remark">
              <el-input v-model="queryParams.remark" placeholder="请输入备注" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-tooltip :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top">
      <div ref="searchIcon" class="search_icon" :class="showSearch ? 'show' : 'hide'" @click="showSearch = !showSearch">
        <svg-icon icon-class="commencement"></svg-icon>
      </div>
    </el-tooltip>

    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between">
          <div class="flex">
            <el-button v-hasPermi="['system:PayAccount:add']" type="primary" plain icon="Plus" v-if="!isAdmin" @click="handleAdd">新增</el-button>

            <el-button v-hasPermi="['system:PayAccount:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              >删除</el-button
            >
            <el-button v-hasPermi="['system:PayAccount:remove']" type="warning" plain icon="Delete" @click="viewDelete()">回收站</el-button>
          </div>
          <div class="flex items-center w-fit gap-5">
            <pagination
              v-show="total > 0"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              :page-sizes="[20, 50, 100, 300]"
              :total="total"
              style="height: 30px; margin: 0; padding: 0 !important"
              @pagination="getList"
            />
            <right-toolbar v-model:showSearch="showSearch" :show-search-btn="false" @query-table="getList"></right-toolbar>
          </div>
        </div>
      </template>

      <el-table v-loading="loading" :data="PayAccountList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="false" label="账号ID" align="center" prop="accountId" />
        <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
        <el-table-column label="账号名称" align="center" prop="accountName" />
        <el-table-column label="供应商" v-if="!isSupplier" align="center" prop="supplierName" />
        <el-table-column label="支付平台/域名" align="center" prop="payTypeId">
          <template #default="{ row }">
            <el-tooltip :content="payList.filter((item) => item.typeId == row.payTypeId)[0]?.name || row.payTypeId">
              <div class="truncate w-[100%]">{{ payList.filter((item) => item.typeId == row.payTypeId)[0]?.name || row.payTypeId }}</div>
            </el-tooltip>
            <el-tooltip :content="row.domain">
              <div class="truncate w-[100%]">{{ row.domain }}</div>
            </el-tooltip>
            <el-tooltip :content="row.ip">
              <div class="truncate w-[100%]">{{ row.ip }}</div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="今日收款单数/金额" width="140" align="center">
          <template #default="{ row }">
            <div>{{ row.payChart?.todayCount }} 单</div>
            <div>USD {{ row.payChart?.todayMoney }}</div>
          </template>
        </el-table-column>
        <!-- <el-table-column label="ip" align="center" prop="ip" /> -->
        <!-- <el-table-column label="插件地址" align="center" prop="plugin" /> -->
        <el-table-column label="支付成功" v-if="!isSupplier" align="center">
          <template #default="{ row }">
            <div
              v-if="row.loading"
              v-loading="row.loading"
              element-loading-background="transparent"
              style="height: 50px; background: transparent"
            ></div>
            <template v-else>
              <template v-if="row.isViewInfo">
                <div>{{ row.successCount }} 单</div>
                <div>USD {{ row.successTotal }}</div>
              </template>
              <template v-else type="primary">
                <div @click="viewAccount(row)" class="cursor-pointer">-</div>
              </template>
            </template>
          </template>
        </el-table-column>

        <el-table-column label="吃单" v-if="shwoEat" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            <div
              v-if="row.loading"
              v-loading="row.loading"
              element-loading-background="transparent"
              style="height: 50px; background: transparent"
            ></div>
            <template v-else>
              <template v-if="row.isViewInfo">
                <div>{{ row.eatCount }} 单</div>
                <div>USD {{ row.eatTotal }}</div>
              </template>
              <template v-else type="primary">
                <div @click="viewAccount(row)" class="cursor-pointer">-</div>
              </template>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="退款" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            <div
              v-if="row.loading"
              v-loading="row.loading"
              element-loading-background="transparent"
              style="height: 50px; background: transparent"
            ></div>
            <template v-else>
              <template v-if="row.isViewInfo">
                <div>{{ row.refundCount }} 单</div>
                <div>USD {{ row.refundTotal }}</div>
              </template>
              <template v-else type="primary">
                <div @click="viewAccount(row)" class="cursor-pointer">-</div>
              </template>
            </template>
          </template>
        </el-table-column>

        <el-table-column label="结算金额" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            <div
              v-if="row.loading"
              v-loading="row.loading"
              element-loading-background="transparent"
              style="height: 50px; background: transparent"
            ></div>
            <template v-else>
              <template v-if="row.isViewInfo">
                <div>{{ row.settCount }} 单</div>
                <div>USD {{ row.settTotal }}</div>
              </template>
              <template v-else type="primary">
                <div @click="viewAccount(row)" class="cursor-pointer">-</div>
              </template>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="API模式" align="center" prop="apiType" show-overflow-tooltip>
          <template #default="{ row }">
            <el-tag v-if="row.apiType" type="primary" class="truncate overflow-hidden max-w-[100%] w-fit" style="justify-content: flex-start">{{
              row.payConfig.apiConfig.find((item) => item.value == row.apiType)?.label
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="70" prop="status">
          <template #default="{ row }">
            <el-tag v-if="row.status == 1" type="success">活跃</el-tag>
            <el-tag v-else-if="row.status == 2" type="danger">封禁</el-tag>
            <el-tag v-else type="danger">失败</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="是否生成订单/产品" align="center" prop="generateOrder" width="110">
          <template #default="{ row }">
            <div class="flex flex-col gap-1 items-cnter">
              <div class="flex items-center gap-2">
                <span>订单:</span>
                <el-tag v-if="row.generateOrder" type="primary">是</el-tag>
                <el-tag v-else type="info">否</el-tag>
              </div>

              <div class="flex items-center gap-2">
                <span>产品:</span>
                <el-tag v-if="row.generateProduct" type="primary">是</el-tag>
                <el-tag v-else type="info">否</el-tag>
              </div>
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column label="账号配置" align="center" prop="config" show-overflow-tooltip /> -->
        <!-- <el-table-column label="代理名称" align="center" prop="agentName" /> -->
        <el-table-column label="操作" align="center" width="220">
          <template #default="scope">
            <el-button v-hasPermi="['system:PayAccount:edit']" link type="primary" icon="View" @click="viewAccount(scope.row)">查看</el-button>
            <el-button v-hasPermi="['system:PayAccount:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button v-hasPermi="['system:PayAccount:remove']" link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
            <el-button v-hasPermi="['system:PayAccount:remove']" link type="primary" icon="Edit" @click="handleUpdate(scope.row, '编辑备注')"
              >编辑备注</el-button
            >
            <el-button v-hasPermi="['system:PayAccount:edit']" link type="primary" icon="CopyDocument" @click="copyAccount(scope.row)"
              >拷贝账号</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div class="flex justify-end mt-5 mr-[-0.5rem]">
        <div class="flex justify-end items-center w-fit gap-5">
          <pagination
            v-show="total > 0"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            :page-sizes="[20, 50, 100, 300]"
            :total="total"
            style="height: 30px; margin: 0; padding: 0 !important"
            @pagination="getList"
          />
          <right-toolbar v-model:showSearch="showSearch" :show-search-btn="false" @query-table="getList"></right-toolbar>
        </div>
      </div>
    </el-card>
    <!-- 添加或修改收款账号对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" :width="dialog.title == '编辑备注' ? '600px' : '70%'" append-to-body>
      <el-form ref="PayAccountFormRef" :model="form" :rules="rules" :label-width="dialog.title == '编辑备注' ? '' : '100px'">
        <el-form-item v-if="dialog.title == '编辑备注'" label="备注" prop="remark">
          <el-input type="textarea" v-model="form.remark" />
        </el-form-item>
        <template v-else>
          <el-form-item label="账号名称" prop="accountName">
            <el-input v-model="form.accountName" placeholder="请输入账号名称" />
          </el-form-item>
          <el-form-item label="支付平台" prop="payTypeId">
            <el-select
              v-model="form.payTypeId"
              @change="
                changePayType();
                form.apiType = '';
              "
            >
              <el-option v-for="item in payList" :label="item.name" :value="item.typeId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="apiConfig.length" label="API模式" prop="apiType">
            <el-select v-model="form.apiType" placeholder="API模式">
              <el-option v-for="item in apiConfig" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="供应商" v-if="!isSupplier" prop="supplierId">
            <el-select v-model="form.supplierId" placeholder="供应商" filterable clearable>
              <el-option v-for="item in supplierList" :label="item.userName" :value="item.userId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="域名" prop="domain">
            <el-input v-model="form.domain" placeholder="请输入域名" />
          </el-form-item>

          <el-form-item label="ip" prop="ip">
            <el-input v-model="form.ip" placeholder="请输入ip" />
          </el-form-item>
          <el-form-item label="插件地址" prop="plugin">
            <el-input v-model="form.plugin" placeholder="请输入插件地址" />
          </el-form-item>
          <el-form-item label="国家验证策略" prop="countryType">
            <el-select v-model="form.countryType" clearable placeholder="请选择国家验证策略">
              <el-option :value="1" label="黑名单"></el-option>
              <el-option :value="2" label="白名单"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="国家" v-if="form.countryType > 0" prop="countryCodeCopy">
            <el-cascader
              v-model="form.countryCodeCopy"
              style="width: 100%"
              placeholder="请选择国家"
              :options="countryOption"
              clearable
              :show-all-levels="false"
              :props="{ multiple: true, checkStrictly: false, emitPath: false }"
              filterable
            />
          </el-form-item>
          <!-- <el-form-item v-for="item in accountItem" :label="item.label">
          <el-input v-model="form.config[item.value]" :placeholder="'请输入' + item.label" />
        </el-form-item> -->
          <el-row>
            <el-col :span="5">
              <el-form-item label="生成订单" prop="generateOrder">
                <el-switch v-model="form.generateOrder" :active-value="1" :inactive-value="0" />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="生成产品" prop="generateProduct">
                <el-switch v-model="form.generateProduct" :active-value="1" :inactive-value="0" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item v-if="form.generateOrder == 1" label="订单状态" prop="orderStatus">
            <el-select v-model="form.orderStatus">
              <el-option v-for="item in approve_order_status" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="form.generateOrder == 1" label="订单来源" prop="orderSource">
            <el-select v-model="form.orderSource" multiple>
              <el-option v-for="item in order_origin" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="账号状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio :value="1">活跃</el-radio>
              <el-radio :value="2">封禁</el-radio>
              <el-radio :value="3">失败</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="账号配置" prop="config">
            <CodeMirror v-model="form.config" />
          </el-form-item>

          <el-form-item label="配置示例" v-hasPermi="['system:config:configExample']">
            <el-tooltip class="box-item" effect="dark" content="点击查看示例" placement="top">
              <el-icon style="font-size: 24px" @click="viewExample"><QuestionFilled /></el-icon>
            </el-tooltip>
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 回收站 -->
    <el-dialog v-model="showDelete" title="回收站" width="1300">
      <el-form inline :model="deleteQueryParams" ref="deleteForm">
        <el-form-item label="账号" prop="accountName">
          <el-input v-model="deleteQueryParams.accountName"></el-input>
        </el-form-item>
        <el-form-item label="供应商" prop="supplierId">
          <el-select v-model="deleteQueryParams.supplierId" filterable clearable>
            <el-option v-for="item in supplierList" :label="item.userName" :value="item.userId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="支付平台" prop="payTypeId">
          <!-- <el-input v-model="queryParams.payTypeId" placeholder="请输入支付平台" clearable @keyup.enter="handleQuery" /> -->
          <el-select v-model="deleteQueryParams.payTypeId" clearable>
            <el-option v-for="item in payList" :key="item.name" :label="item.name" :value="item.typeId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="getDeleteList">搜索</el-button>
          <el-button icon="Refresh" @click="resetDelete">重置</el-button>
        </el-form-item>
      </el-form>
      <div>
        <el-button type="primary" plain @click="changeRestoreAccounts">全部还原</el-button>
        <el-button type="danger" plain @click="changeDeleteAccounts" v-if="isAdmin">全部删除</el-button>
      </div>
      <el-table v-loading="deleteLoading" :data="deleteList" class="mt-[20px]">
        <el-table-column label="账号名称" align="center" prop="accountName" />
        <el-table-column label="供应商" v-if="!isSupplier" align="center" prop="supplierName" />
        <el-table-column label="支付平台" align="center" prop="payTypeId">
          <template #default="{ row }">
            <div>{{ payList.filter((item) => item.typeId == row.payTypeId)[0]?.name || row.payTypeId }}</div>
          </template>
        </el-table-column>

        <el-table-column label="支付成功" align="center">
          <template #default="{ row }">
            <div
              v-if="row.loading"
              v-loading="row.loading"
              element-loading-background="transparent"
              style="height: 50px; background: transparent"
            ></div>
            <template v-else>
              <template v-if="row.isViewInfo">
                <div>{{ row.successCount }} 单</div>
                <div>USD {{ row.successTotal }}</div>
              </template>
              <template v-else type="primary">
                <div @click="viewAccount(row)" class="cursor-pointer">-</div>
              </template>
            </template>
          </template>
        </el-table-column>

        <el-table-column label="吃单" v-if="shwoEat" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            <div
              v-if="row.loading"
              v-loading="row.loading"
              element-loading-background="transparent"
              style="height: 50px; background: transparent"
            ></div>
            <template v-else>
              <template v-if="row.isViewInfo">
                <div>{{ row.eatCount }} 单</div>
                <div>USD {{ row.eatTotal }}</div>
              </template>
              <template v-else type="primary">
                <div @click="viewAccount(row)" class="cursor-pointer">-</div>
              </template>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="退款" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            <div
              v-if="row.loading"
              v-loading="row.loading"
              element-loading-background="transparent"
              style="height: 50px; background: transparent"
            ></div>
            <template v-else>
              <template v-if="row.isViewInfo">
                <div>{{ row.refundCount }} 单</div>
                <div>USD {{ row.refundTotal }}</div>
              </template>
              <template v-else type="primary">
                <div @click="viewAccount(row)" class="cursor-pointer">-</div>
              </template>
            </template>
          </template>
        </el-table-column>

        <el-table-column label="结算金额" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            <div
              v-if="row.loading"
              v-loading="row.loading"
              element-loading-background="transparent"
              style="height: 50px; background: transparent"
            ></div>
            <template v-else>
              <template v-if="row.isViewInfo">
                <div>{{ row.settCount }} 单</div>
                <div>USD {{ row.settTotal }}</div>
              </template>
              <template v-else type="primary">
                <div @click="viewAccount(row)" class="cursor-pointer">-</div>
              </template>
            </template>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="220">
          <template #default="scope">
            <el-button link type="primary" @click="changeRestoreAccounts(scope.row)">还原</el-button>
            <el-button link type="danger" v-if="isAdmin" @click="changeDeleteAccounts(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        v-model:page="deleteQueryParams.pageNum"
        v-model:limit="deleteQueryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="deleteTotal"
        style="height: 30px; margin-top: 20px; padding: 0 !important"
        @pagination="viewDelete"
      />
    </el-dialog>
  </div>
</template>

<script setup name="PayAccount" lang="ts">
import CodeMirror from '@/components/CodeMirror/index.vue';
import { getClient } from '@/api/pay/PayApp';
import {
  listPayAccount,
  getPayAccount,
  delPayAccount,
  addPayAccount,
  updatePayAccount,
  getPayChart,
  restoreAccounts,
  restoreAccountsAll,
  deleteAccounts,
  deleteAccountsAll
} from '@/api/pay/PayAccount';
import { listCount } from '@/api/pay/PayOrder';
import { PayAccountVO, PayAccountQuery, PayAccountForm } from '@/api/pay/PayAccount/types';
import { selecTypetList } from '@/api/pay/PayType/index';
import useUserStore from '@/store/modules/user';
import { listUser } from '@/api/system/user';

const isAdmin = computed(() => {
  const { isAdmin } = useUserStore();
  return isAdmin;
});

const isSupplier = computed(() => {
  const { isSupplier } = useUserStore();
  return isSupplier;
});

const shwoEat = computed(() => {
  return !useUserStore().isClient && useUserStore().isFeign;
});

const supplierList = ref([]);
const getSupplier = () => {
  if (!isSupplier.value) {
    listUser({ pageSize: 2000, pageNum: 1, roleKey: 'supplier' }).then((res) => {
      supplierList.value = res.rows;
    });
  }
};
getSupplier();

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { order_origin, approve_order_status } = toRefs(proxy?.useDict('order_origin', 'approve_order_status'));

const PayAccountList = ref<PayAccountVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(false);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const PayAccountFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: PayAccountForm = {
  accountName: undefined,
  payTypeId: undefined,
  domain: undefined,
  ip: undefined,
  plugin: undefined,
  status: 1,
  apiType: undefined,
  generateOrder: undefined,
  generateProduct: undefined,
  orderSource: undefined,
  config: undefined,
  orderStatus: 'completed'
};
// 域名校验
const validatePass2 = (rule, value, callback) => {
  // 去除前后空格
  if (!value) {
    callback(new Error('请输入域名'));
    return;
  }
  let trimmedValue = value.trim();
  const reg = new RegExp(/^(https?:\/\/)([0-9a-zA-Z-]+\.)+[a-zA-Z]{2,}(?:\/.*)?$/);
  if (!reg.test(trimmedValue)) {
    callback(new Error('请输入正确的域名地址'));
  } else if (trimmedValue.endsWith('/')) {
    form.value.domain = trimmedValue.slice(0, -1);
    callback();
  } else {
    form.value.domain = trimmedValue;
    callback();
  }
};
const data = reactive<PageData<PayAccountForm, PayAccountQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    accountName: undefined,
    payTypeId: undefined,
    domain: undefined,
    ip: undefined,
    plugin: undefined,
    status: undefined,
    apiType: undefined,
    generateOrder: undefined,
    generateProduct: undefined,
    config: undefined,
    agentId: undefined,
    params: {}
  },
  rules: {
    accountName: [{ required: true, message: '账号名称不能为空', trigger: 'blur' }],
    payTypeId: [{ required: true, message: '支付平台ID不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '状态不能为空', trigger: 'change' }],
    generateOrder: [{ required: true, message: '是否生成订单不能为空', trigger: 'blur' }],
    generateProduct: [{ required: true, message: '是否生成产品不能为空', trigger: 'blur' }],
    orderSource: [{ required: true, message: '订单来源不能为空', trigger: 'blur' }],
    apiType: [{ required: true, message: 'API模式不能为空', trigger: 'blur' }],
    domain: [{ required: true, message: '域名不能为空', trigger: 'blur' }],
    orderStatus: [{ required: true, message: '订单状态不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询收款账号列表 */
const getList = async () => {
  loading.value = true;
  const res = await listPayAccount(queryParams.value);
  PayAccountList.value = res.rows.map((item) => {
    item.payConfig = payList.value.find((payType) => payType.typeId == item.payTypeId)?.config
      ? JSON.parse(payList.value.find((payType) => payType.typeId == item.payTypeId)?.config.replace(/\/\/\*\*\*.*\*\*\*.*\n/g, ''))
      : '';
    item.isViewInfo = false;
    return item;
  });
  total.value = res.total;
  loading.value = false;
  if (res.total > 0) {
    getPayChartList();
  }
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  PayAccountFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: PayAccountVO[]) => {
  ids.value = selection.map((item) => item);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加收款账号';
  form.value.orderSource = order_origin.value.map((item) => item.value);
  form.value.generateOrder = 1;
  form.value.generateProduct = 1;
};
/**拷贝账号 */
let isCopy = false;
const copyAccount = async (row) => {
  isCopy = true;
  reset();
  const _accountId = row?.accountId;
  const res = await getPayAccount(_accountId);
  form.value = res.data;
  form.value.config == null ? (form.value.config = '') : '';
  form.value.orderSource = form.value?.orderSource ? form.value?.orderSource.split(',') : [];
  dialog.visible = true;
  dialog.title = '拷贝收款账号';
  delete form.value.accountId;
  changePayType();
};

/** 修改按钮操作 */
const handleUpdate = async (row?: PayAccountVO, title?: string) => {
  reset();
  const _accountId = row?.accountId || ids.value[0];
  console.log(_accountId, '_accountId_accountId');
  console.log(row?.accountId, 'row?.accountIdrow?.accountId');

  const res = await getPayAccount(_accountId);
  form.value = res.data;
  form.value.config == null ? (form.value.config = '') : '';

  form.value.orderSource = form.value?.orderSource ? form.value?.orderSource.split(',') : [];

  dialog.visible = true;
  if (title) {
    dialog.title = title;
  } else {
    dialog.title = '修改收款账号';
  }
  form.value.countryCodeCopy = res.data.countryCode?.split(',');
  changePayType();
};

/** 提交按钮 */
const submitForm = () => {
  PayAccountFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (form.value.config) {
        if (!isJSON(form.value?.config.replace(/\/\/\*\*\*.*\*\*\*.*\n/g, ''))) {
          ElMessage.error('JSON格式不对');
          return;
        }
      }
      if (form.value.countryCodeCopy) {
        form.value.countryCode = form.value.countryCodeCopy.join(',');
      }
      form.value.orderSource = form.value.orderSource.join(',');

      if (!form.value.countryType) {
        form.value.countryType = '';
      }

      buttonLoading.value = true;
      if (form.value.accountId && !isCopy) {
        await updatePayAccount(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addPayAccount(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      isCopy = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: PayAccountVO) => {
  const _accountIds = row?.accountId || ids.value.map((item) => item.accountId);
  const _accountNames = row?.accountName || ids.value.map((item) => item.accountName);
  await proxy?.$modal.confirm('是否确认删除收款账号 ' + _accountNames + ' 的数据？').finally(() => (loading.value = false));
  await delPayAccount(_accountIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/PayAccount/export',
    {
      ...queryParams.value
    },
    `PayAccount_${new Date().getTime()}.xlsx`
  );
};

/**获取支付平台 */
const payList = ref([]);
const apiConfig = ref([]);
const getPayList = async () => {
  let res = await selecTypetList();
  payList.value = res.data;
};
/**自定义参数 */
const accountItem = ref([]);
/**切换支付平台 */
const changePayType = () => {
  let config = payList.value.find((item) => item.typeId == form.value.payTypeId)?.config.replace(/\/\/\*\*\*.*\*\*\*.*\n/g, '');
  if (isJSON(config)) {
    if (JSON.parse(config).apiConfig) {
      apiConfig.value = JSON.parse(config).apiConfig;
      accountItem.value = JSON.parse(config).accountItem;
    } else {
      apiConfig.value = [];
    }
  } else {
    apiConfig.value = [];
  }
};

function isJSON(str) {
  if (typeof str == 'string') {
    try {
      var obj = JSON.parse(str);
      if (typeof obj == 'object' && obj) {
        return true;
      } else {
        return false;
      }
    } catch (e) {
      return false;
    }
  }
}

/**
 * 获取收款账号订单统计
 */
const getPayChartList = async () => {
  loading.value = true;
  let ids = PayAccountList.value.map((item) => item.accountId);
  let res = await getPayChart(ids);
  PayAccountList.value.map((item) => {
    item.payChart = res.data.find((item2) => item2.accountId == item.accountId);
    item.loading = false;
    return item;
  });
  loading.value = false;
};

const viewExample = () => {
  window.open('/accountConfigExamplet');
};

const showDelete = ref(false);
const deleteList = ref([]);
const deleteQueryParams = ref({
  pageNum: 1,
  pageSize: 10,
  isDelete: 1,
  supplierId: '',
  accountName: ''
});
const deleteLoading = ref(true);
const deleteTotal = ref(0);
const viewDelete = () => {
  showDelete.value = true;
  getDeleteList();
};
const getDeleteList = () => {
  deleteLoading.value = true;
  listPayAccount(deleteQueryParams.value).then((res) => {
    deleteList.value = res.rows.map((item) => {
      item.isViewInfo = false;
      return item;
    });
    deleteTotal.value = res.total;
    deleteLoading.value = false;
  });
};
const deleteForm = ref(null);
const resetDelete = () => {
  deleteQueryParams.value.supplierId = '';
  deleteQueryParams.value.accountName = '';
  getDeleteList();
};

const viewAccount = async (row) => {
  row.loading = true;
  listCount({ accountId: row.accountId }).then((res) => {
    Object.assign(row, res.data);
    getPayAccount(row.accountId).then((res) => {
      Object.assign(row, res.data);
      row.isViewInfo = true;
      row.loading = false;
    });
  });
};

const changeRestoreAccounts = (row) => {
  ElMessageBox.confirm('确定要还原账号数据吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    if (row.accountId) {
      restoreAccounts(row.accountId).then((res) => {
        ElMessage.success('还原成功');
        viewDelete();
      });
    } else {
      restoreAccountsAll().then((res) => {
        ElMessage.success('还原成功');
        viewDelete();
      });
    }
  });
};

const changeDeleteAccounts = (row) => {
  ElMessageBox.confirm('确定要删除账号数据吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    if (row.accountId) {
      deleteAccounts(row.accountId).then((res) => {
        ElMessage.success('删除成功');
        viewDelete();
      });
    } else {
      deleteAccountsAll().then((res) => {
        ElMessage.success('删除成功');
        viewDelete();
      });
    }
  });
};
const countryOption = ref([]);
onMounted(async () => {
  await getPayList();
  await getList();
  proxy?.getConfigKey('sys.country.list').then((response: any) => {
    countryOption.value = JSON.parse(response.data);
  });
});
</script>

<style lang="scss" scoped>
:deep(.el-form-item__label) {
  width: fit-content;
}
:deep(.el-tag__content) {
  max-width: 100%;
  text-overflow: ellipsis;
  overflow: hidden;
}
</style>
